<?php
//$game_id = holds what game it is. duh...
$gamearr = select_from_db(array('name','map','owner_id','active','timeleft'),array('games'),array("id=$game_id"));
$name = $gamearr[0]['name'];
$owner = $gamearr[0]['owner_id'];
$timeleft = $gamearr[0]['timeleft'];
$map = $gamearr[0]['map'];
$userid = $_SESSION['user_id'];

if($owner == $userid){
	
}

$userlandarr = select_from_db(array('land','started'),array('users__got__games'),array("user_id=$userid","game_id=$game_id"));
$userland = $userlandarr[0]['land'];
$active = $userlandarr[0]['started'];

$provincearr = select_from_db(array('name','x','y','neighbors'),array('province'),array("mapname='$map'"));

//create title, map and canvas
$jsstring = "
	<div id='mainGameBanner'>
		<h2 id='mainGameTitle' class='elevenSixteenths'>$name</h2>
		<div id='mainGameTimer' class='right fiveSixteenths'>
			<span id='gameTimer'>$timeleft</span>
		</div>
	</div>
	<canvas id='canvas' width='960' height='804' style='position: absolute'></canvas>
	<img src='images/$map/mapfront.jpg' id='gamemap'/>
	<div id='movebox'>
		<div id='moveboxmove'>Move/Attack</div>
		<div id='moveboxsupportatk'>Support attack</div>
		<div id='moveboxsupportdef'>Support defence</div>
	</div>
";

$armyobjects = "";

$unitmovearray = array();

if($active == 0){
	$armydir = opendir("images/$map/units/");
	while(false != ($file = readdir($armydir))){
		if($file != "." && $file != ".."){

			$jsonread = file_get_contents("images/$map/units/" . $file, 'r');

			$jsoncontent = json_decode($jsonread);

			$unitland = $jsoncontent -> land;
			$unitid = $jsoncontent -> unitid;
			$unitprovince = $jsoncontent -> province;
			$unitcolor = $jsoncontent -> color;

			$values['unit'] = '#' . $unitid;
			$values['action'] = 'Hold';
			$values['target'] = $unitprovince;
			$values['game_id'] = $game_id;
			$values['user_id'] = $userid;

			$jsstring .= "<img src='images/$unitcolor" . "army.png' class='army' id='$unitid'>";

			if($unitland == $userland){
				$armyobjects .= "var $unitid = new Unit('#$unitid'); $unitid.stickarmy($unitprovince);\n";
				insert_to_db(array('nation' => $unitland, 'color' => $unitcolor, 'unitid' => $unitid, 'user_id' => $userid, 'province' => $unitprovince, 'game_id' => $game_id), 'army');
				insert_to_db($values,'moves');
			}else{
				$armyobjects .= "var $unitid = new UnitGeneral('#$unitid'); $unitid.stickarmy($unitprovince);\n";
			}
		}
	}
}else{
	$armyarr = select_from_db(array('*'),array('army'),array("game_id=$game_id"));
	//print_r($armyarr);
	foreach($armyarr as $armyinfo){
		$unitid = $armyinfo['unitid'];
		$unitprovince = $armyinfo['province'];
		$unitland = $armyinfo['nation'];
		$unitcolor = $armyinfo['color'];

		$jsstring .= "<img src='images/$unitcolor" . "army.png' class='army' id='$unitid'>";

		if($unitland == $userland){
			$armyobjects .= "var $unitid = new Unit('#$unitid'); $unitid.stickarmy($unitprovince);\n";
		}else{
			$armyobjects .= "var $unitid = new UnitGeneral('#$unitid'); $unitid.stickarmy($unitprovince);\n";
		}
	}
}

$jsstring .= "<script type='text/javascript'>";

//size from mapedge to windowedge
$jsstring .= "
var widthofwindow = $(window).width();
widthofwindow = widthofwindow-960;
windowsize = widthofwindow/2;

$('#movebox').hide();

//setTimeout(
//updateTimer();
setTimeout('fetchTime()',5000);

function fetchTime(){
	$.post('controller/fetchTimer.php', {'gameid' : $game_id},
		function(timer){
			if(timer=='slut'){
				alert('end of round!');
			}else{
				$('#gameTimer').html(timer);
				setTimeout('fetchTime()',5000);
			}
	});
}

";

$dir = opendir("images/$map/maps/coords/");

//preload images
while(false != ($file = readdir($dir))){
	if($file != "." && $file != ".."){
		$file = strstr($file, '.', TRUE);
		$jsstring .= "var front$file = new Image(); front$file.src = 'images/$map/maps/front$file.png';\n";
	}
}

$jsstring .= "
";

//PROVINCES
foreach($provincearr as $province){
	$provinceid = $province['name'];
	$provincex = $province['x'];
	$provincey = $province['y'];
	$neighbors = $province['neighbors'];

	if($neighbors != null)
		$jsstring .= "var $provinceid = new Province('$provinceid',$provincex,$provincey,$neighbors);\n";
	else
		$jsstring .= "var $provinceid = new Province('$provinceid',$provincex,$provincey);\n";

}

$jsstring .= $armyobjects;


//unit class general, for all units
$jsstring .= "
function UnitGeneral(name){
	var province;
	this.stickarmy = function(whatprovince){
		province = whatprovince;
		x = whatprovince.stickx + windowsize;
		y = whatprovince.sticky + 160;
		$(name).css('left', x).css('top', y);
		whatprovince.currentarmy(this);
	}
}
\n";

//unit class for user
$jsstring .= "
function Unit(name){
	var province;
	var move = true;
	var click = 0;
	var that = this;

	this.stickarmy = function(whatprovince){
		province = whatprovince;

		x = whatprovince.stickx + windowsize;
		y = whatprovince.sticky + 160;
		if(whatprovince.whatarmy){
			x += 10; y -= 10;
		}
		whatprovince.currentarmy(this);

		$(name).css('left', x).css('top', y);
	}
	$(name).click(function(e){
		if(click == 1){
			var X = e.pageX - windowsize;
			var Y = e.pageY - 160;
			var data = context.getImageData(X, Y, 1, 1).data;
			if(data[3]>0){
				$.post('controller/findprovince.php', {'x' : X, 'y' : Y, 'map' : '$map'},
					function(whatprovince){
						whatprovince = eval(whatprovince);
						$('#movebox').css('left', (whatprovince.stickx + windowsize)).css('top', (whatprovince.sticky+30));
						$(name).css('left', (whatprovince.stickx + windowsize)).css('top', (whatprovince.sticky+100));
						$('#movebox').fadeIn(600);
						
						$('#moveboxmove').click(function(e){
							$.post('controller/savemoves.php', {'unitid' : name, 'action' : 'move', 'target' : whatprovince.name, 'gameid' : $game_id, 'userid' : $userid},
							function(d){
								console.debug('move');
								$('#movebox').fadeOut();
							});
						});
						$('#moveboxsupportatk').click(function(e){
							$.post('controller/savemoves.php', {'unitid' : name, 'action' : 'supportatk', 'target' : whatprovince.name, 'gameid' : $game_id, 'userid' : $userid},
							function(d){
								console.debug('support atk');
								$('#movebox').fadeOut();
							});
						});
						$('#moveboxsupportdef').click(function(e){
							$.post('controller/savemoves.php', {'unitid' : name, 'action' : 'supportdef', 'target' : whatprovince.name, 'gameid' : $game_id, 'userid' : $userid},
							function(d){
								console.debug('support def');
								$('#movebox').fadeOut();
							});
						});
					});
				move = false;
				click = 0;
				drawMap();
			}
		}else{
			click = 1;
			move = true;
		}
		$(document).mousemove(function(e){
			if(move == true){
				$(name).css('left', e.pageX).css('top', e.pageY);
			}
		});
		drawMap(province.neighbors);
	});
}
\n";

//province class, stick = position of army, currenctarmy = function to add army to province
$jsstring .= "
function Province(name,x, y){
	this.name = name;
	this.stickx = x; this.sticky = y;
	this.neighbors = new Array();
	for(var i=3;i<arguments.length;i++){
		this.neighbors[i-3] = arguments[i];
	}
	this.currentarmy = function(whatarmy){
		this.whatarmy = whatarmy;
	}
}
\n";

$jsstring .= "
function drawMap(){
	context = document.getElementById('canvas').getContext('2d');
	context.clearRect(0,0,960,804);
	imag = arguments[0];
	for(var i=0;i<imag.length;i++){
		context.drawImage(imag[i], 0, 0);
	}
}
";

$jsstring .= "</script>";

echo $jsstring;
update_db(array('started' => '1'), 'users__got__games', "user_id = $userid")
?>